//
//  task.m
//  iCodeMacRun
//
//  Created by Andrew Barry on 21/06/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "task.h"

jsobject *taskObject;

static jsvalue taskRunMethod(jscontext *cx, jsframe *outer, jsvalue me, jsvalue *argv, int argc) {
	if (argc < 1)
		return JSVAL_VOID;
	
	jsvalue obj = argv[0];
	
	NSString *path = jsgetstring(cx, obj, 0, "path", nil);
	
	if (!path || [path length] == 0)
		return JSVAL_VOID;
	
	jsvalue arguments = JSVAL_VOID;
	NSMutableArray *args = [NSMutableArray new];
	
	arguments = jsget(cx, obj, 0, "arguments");
	if (arguments != 0 && JSVAL_IS_OBJECT(arguments)) {
		if (isArray(arguments)) {
			int len;
			len = jsarraylength(arguments);
			for (int idx = 0; idx < len; idx++) {
				jsvalue item = jsarrayelem(arguments, idx);
				NSString *str =  jsasstrRetain(cx, item);
				[args addObject:str];
				[str release];
			}
		}
	}

	NSString *dirPath = jsgetstring(cx, obj, 0, "currentDirectory", nil);	
	NSPipe *outputPipe = [NSPipe new];
	
	NSTask *task = [NSTask new];
	[task setLaunchPath:path];
	[task setArguments:args];
	if (dirPath != nil) {
		[task setCurrentDirectoryPath:dirPath];
	}
	[task setStandardOutput:outputPipe];
	[task launch];
	
	NSFileHandle *outHandle = [outputPipe fileHandleForReading];
	NSData *data = [outHandle readDataToEndOfFile];
	
	NSString *result = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
	[task waitUntilExit];
	int exitCode = [task terminationStatus];
	[task release];
	[outputPipe release];
	
	jsvalue rv = jsnewobject(cx);
	
	jsaddroot(cx, &rv);
	
	jsset(cx, rv, 0, "output", jsstrFromNSString(cx, result));
	jsset(cx, rv, 0, "exitCode", jsnumi(cx, exitCode));

	jsremoveroot(cx, &rv);

	return rv;
}

void registerTask(jscontext *cx) {
	jsset(cx, cx->slots[13], 0, "execute", bindFunction(cx, taskRunMethod));
}

/*
static JSClass taskClass = {"Task", JSCLASS_HAS_RESERVED_SLOTS(2), 
JS_PropertyStub,JS_PropertyStub,JS_PropertyStub,JS_PropertyStub, 
JS_EnumerateStub,JS_ResolveStub,JS_ConvertStub,taskFinalizer 
};

static JSPropertySpec taskProps[] = {
{0, 0, 0, 0, 0}
};

static JSFunctionSpec taskFunctions[] = {
{"run", taskRunMethod, 0, 0, 0 },
{0, 0, 0, 0, 0}
};


*/